package com.fingard.dsp.bank.directbank.cmbc02;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;
import java.util.*;

public class CMBC02Statement extends CMBC02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        String totalNum = "";
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem == null) {
                tmpRespCode = "-1";
                tmpRespInfo = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息";
                retAts.writeRespCode(tmpRespCode);
                retAts.writeRespInfo(tmpRespInfo);
                return retAts;
            }
            Date date = Format.Date8Format.parse(p_reqQrySttm.busDate);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, 1);
            // 组装请求报文
            String version = "v1.0";
            String source = "PC";
            String merchantNum = actItem.merchantId;
            String tmpTransSeqID = p_reqQrySttm.reqHeader.transSeqID;
            String merchantSeq = "";
            boolean padSingleSeq50 = getBankConfig().getValueAsBool("padSingleSeq50");
            this.WriteBankLogLn("padSingleSeq50:" + padSingleSeq50);
            if (padSingleSeq50) {
                merchantSeq = actItem.merchantId + "_" + tmpTransSeqID + "_";
                merchantSeq = StringHelper.padByByte(merchantSeq, this.getCharset(reqHeader.transType), 50, '0', 'R');
            }
            String transDate = Format.Date8Format.format(p_reqQrySttm.getBusDate());
            String transTime = Format.Time9Format.format(cal.getTime());
            String transCode = "PAY_F001";
            String securityType = "SM203";
            String reserve1 = "";
            String reserve2 = "";
            String reserve3 = "";
            String reserve4 = "";
            String reserve5 = "";
            String reserveJson = "";
            // 组装业务报文
            String fileTranDate = p_reqQrySttm.busDate;
            String fileType = "detail";
            String segmentIndex = "0";
            String contractId = "";
            if ("F".equals(p_reqQrySttm.statementType)) {
                contractId = actItem.getBusCode("payStatement");
            } else {
                contractId = actItem.getBusCode("recStatement");
            }

            Map<String, Object> messagetoBank = new HashMap<String, Object>();
            messagetoBank.put("version", version);
            messagetoBank.put("source", source);
            messagetoBank.put("merchantNum", merchantNum);
            messagetoBank.put("merchantSeq", merchantSeq);
            messagetoBank.put("transDate", transDate);
            messagetoBank.put("transTime", transTime);
            messagetoBank.put("transCode", transCode);
            messagetoBank.put("securityType", securityType);
            messagetoBank.put("reserve1", reserve1);
            messagetoBank.put("reserve2", reserve2);
            messagetoBank.put("reserve3", reserve3);
            messagetoBank.put("reserve4", reserve4);
            messagetoBank.put("reserve5", reserve5);
            messagetoBank.put("reserveJson", reserveJson);
            messagetoBank.put("fileTranDate", fileTranDate);
            messagetoBank.put("fileType", fileType);
            messagetoBank.put("segmentIndex", segmentIndex);
            messagetoBank.put("contractId", contractId);

            Map<String, Object> submitMap = new HashMap<String, Object>();
            Map<String, Object> busiMap = new HashMap<String, Object>();
            splidReqMap1(messagetoBank, submitMap, busiMap);
            submitMap.put("businessContext", encodeMsgToString1(p_reqQrySttm.actNum, busiMap));

            WriteBankLogLn("第0次发送给银行的报文：" + submitMap.toString());
            String tmpUrl = bankFront.getUrl("Statement");
            WriteBankLogLn("tmpurl: " + tmpUrl);
            Map<String, Object> reMap = getResponseFromCMBC(submitMap, tmpUrl);
            reMap = convertMapToMap(reMap);
            WriteBankLogLn("第0次解析后银行返回的map对象：" + reMap);
            String returnMessage = reMap.get("businessContext").toString();
            String returnbody = decodeMsgToString(p_reqQrySttm.actNum, returnMessage);
            reMap.remove("businessContext");
            Map<String, String> str  = (Map<String, String>) JSON.parse(returnbody.toString());
            reMap.putAll(str);
            String currentSegment = (String)reMap.get("currentSegmentContentBase64String");
            byte[] baseMerge = getFromBase64(currentSegment);
            byte[] base = null;
            base = getMergeBytes(base, baseMerge);

            JSONArray fileSegments = JSON.parseArray(reMap.get("fileAllSegments").toString());
            int maxCount = fileSegments.size();
            for (int count = 1; count < maxCount; count++) {
                busiMap.remove("segmentIndex");
                busiMap.put("segmentIndex", count + "");
                submitMap.remove("businessContext");
                submitMap.put("businessContext", encodeMsgToString1(p_reqQrySttm.actNum, busiMap));
                WriteBankLogLn("第"+ count +"次发送给银行的报文：" + submitMap.toString());
                Map<String, Object> respMapN = getResponseFromCMBC(submitMap, tmpUrl);
                respMapN = convertMapToMap(respMapN);
                WriteBankLogLn("第"+ count +"次解析后银行返回的map对象：" + respMapN);
                returnMessage = respMapN.get("businessContext").toString();
                returnbody = decodeMsgToString(p_reqQrySttm.actNum, returnMessage);
                str = (Map<String, String>) JSON.parse(returnbody.toString());
                respMapN.remove("businessContext");
                respMapN.putAll(str);
                currentSegment = (String) respMapN.get("currentSegmentContentBase64String");
                byte[] baseMergeN = getFromBase64(currentSegment);
                base = this.getMergeBytes(base, baseMergeN);
            }
            String downFileName = p_reqQrySttm.actNum + p_reqQrySttm.busDate + ".txt";
            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            String file = new String(base, getCharset());
            file = base64ToString(file);
            FileHelper.writeFile(localFilePath, file, getCharset());
            WriteBankLogLn2("民生对账单保存本地路径:" + localFilePath);
            StringBuilder sbFileContent = new StringBuilder();
            sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset()));
            if (StringHelper.hasAnyChar(sbFileContent.toString())) {
                String fileContent = sbFileContent.toString();
                WriteBankLogLn("Base64解密后的fileContent：" + fileContent);
                //将解密后的文件进行分解
                //解析返回文件的数据
                String[] totalLine = fileContent.split("\n");
                String[] head = totalLine[0].split("\\|");
                totalNum = head[1];
                WriteBankLogLn("共获取：" + head[1] + "条对账单");
                for (int i = 1; i < totalLine.length - 1; i++) {
                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                    String[] transbody = totalLine[i].split("\\|");
                    //0=待处理;1=成功;2=失败;R=异常
                    if (transbody[15].length() > 6) {
                        transbody[15] = transbody[15].substring(0, 6);
                    }
                    String[] tmpAskNumber = transbody[4].split("_");
                    tmpRetDetail.busTime = transbody[14] + transbody[15];
                    tmpRetDetail.bkSeq = transbody[3];

                    tmpRetDetail.amount = transbody[6];
                    tmpRetDetail.busType = transbody[11];
                    tmpRetDetail.memo = transbody[10];
                    tmpRetDetail.refundAmt = transbody[7];
                    if (tmpAskNumber.length > 1) {
                        tmpRetDetail.askNumber = tmpAskNumber[1];
                    }
                    if ("F".equals(p_reqQrySttm.statementType)) {
                        tmpRetDetail.cdFlag = "27";
                    } else {
                        tmpRetDetail.cdFlag = "22";
                    }
                    tmpRetDetail.transState = TransState.Success;
                    retAts.writeRetDetail(tmpRetDetail);
                }
            } else {
                tmpRespCode = "0";
                tmpRespInfo = sbFileContent.toString();
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }
        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("代收付对账单获取失败,原因:[" + tmpRespInfo + "]");
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            } else {
                // 获取成功时写入总笔数
                retAts.isWritedTotalNum(String.valueOf(totalNum));
            }
        }
        retAts.writeEnd();
        return retAts;
    }
}
